const express = require('express')
const Result = require('../models/Result')
const { login, findUser } = require('../services/user')
const { md5, decoded } = require('../utils')
const { PWD_SALT, PRIVATE_KEY, JWT_EXPIRED} = require('../utils/constant')
const { body, validationResult } = require('express-validator')
const boom = require('boom')
// jwt
const jwt = require('jsonwebtoken')
const router = express.Router()

// login
router.post('/login',
    [
        body('username').isString().withMessage('用户名必须为字符'),
        body('password').isString().withMessage('密码必须为字符')
    ],
    function (req, res, next) {
        // console.log(req.body)
        const err = validationResult(req)
        if(!err.isEmpty()){
            const [{msg}] = err.errors
            next(boom.badRequest(msg))
        }else{
            let username = req.body.username
            let password = req.body.password
            password = md5(`${password}${PWD_SALT}`)
            console.log(password)
            login(username, password).then(user =>{
                if(!user || user.length === 0){
                    new Result('登录失败').fail(res)
                }else{
                    // 生成jwt
                    const token = jwt.sign(
                        {username},
                        PRIVATE_KEY,
                        { expiresIn: JWT_EXPIRED }
                    )

                    new Result({ token }, '登录成功').success(res)
                }
            })
        }
    })

router.get('/info', function(req, res, next) {
    let token_username = decoded(req)
    findUser(token_username.username).then(user => {
        if(user){
            user.roles = [user.role]
            new Result(user, '用户信息查询成功').success(res)
        }else{
            new Result('用户信息查询失败').fail(res)
        }
    })
})

module.exports = router